package initialize

import (
	"context"
	"github.com/pkg/errors"
	"github.com/redis/go-redis/v9"
	"strconv"
	"time"
	"user_srv/global"
)

func InitRedis() {
	global.RedisClient = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})
}

// 五分钟发送三次
func SendSms(mobile string) error {
	key := mobile + "_sms_limit"
	now := time.Now()
	BeforeFive := strconv.FormatInt(now.Add(-5*time.Minute).Unix(), 10)
	result, err := global.RedisClient.ZCount(context.Background(), key, BeforeFive, strconv.FormatInt(time.Now().Unix(), 10)).Result()
	if err != nil {
		return err
	}
	if result >= 3 {
		return errors.New("五分钟最多发三次")
	}
	_, err = global.RedisClient.ZAdd(context.Background(), key, redis.Z{
		Score:  float64(now.Unix()),
		Member: now.Unix(),
	}).Result()
	if err != nil {
		return err
	}
	return nil
}
